package cn.laixueit.cart.service.impl;

import cn.laixueit.mapper.BrandMapper;
import cn.laixueit.cart.pojo.item.Brand;
import cn.laixueit.cart.pojo.page.PageResult;
import cn.laixueit.cart.service.BrandService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class BrandServiceImpl extends ServiceImpl<BrandMapper, Brand> implements BrandService {

    @Autowired
    private BrandMapper brandMapper;

    @Override
    public PageResult<Brand> findPage(String key, Integer page, Integer rows, String sortBy, Boolean desc) {

        PageResult<Brand> pageResult = new PageResult<>();

        Page<Brand> p = new Page<>(page, rows);
        QueryWrapper<Brand> wrapper = getWrapper(key, sortBy, desc);
        IPage<Brand> brandIPage = page(p,wrapper);

        pageResult.setItems(brandIPage.getRecords());
        pageResult.setTotal(brandIPage.getTotal());
        return pageResult;
    }

    @Override
    @Transactional
    public void saveBrandAndCategory(Brand brand, List<Long> cids) {
        save(brand);
        for (Long cid : cids) {
            brandMapper.savecategoryAndBrand(cid,brand.getId());
        }
    }

    @Override
    public List<Brand> cid(Long cid) {

        return brandMapper.cid(cid);
    }

    private QueryWrapper<Brand> getWrapper(String key, String sortBy, Boolean desc){
        QueryWrapper<Brand> wrapper = new QueryWrapper<>();
        if(key!=null){
            wrapper.like("name",key);
        }
        if(sortBy!=null){
            if(desc){
                wrapper.orderByDesc(sortBy);
            }
        }
        return wrapper;
    }
}
